package com.linjiu.xpermissionclent;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.permissions.IPermissionInterceptor;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.OnPermissionPageCallback;
import com.hjq.permissions.XXPermissions;

import java.util.List;

/**
 * 项目名称：com.linjiu.xpermissionclent
 * 创建人:LuoFG
 * 创建时间:2022/11/15  14:30
 * 描述:
 * 作用:这里只是对外暴露了方法   目前使用的XXPermissions  后续如需维护可替换为其他框架。
 */
public class XPermissionClient {

    private Context context;
    private Activity activity;
    private boolean isShowPermissionDialogTopTips = false;//审核要求的顶部dialog提示弹窗，通用的，不需要可自行去自定义显示它
    private String strTopTipsTitle, strTopTipsContent;
    private PermissionPopWindow permissionPopWindow;

    public static final Handler HANDLER = new Handler(Looper.getMainLooper());

    /**
     * 权限申请标记
     */
    private boolean mRequestFlag;


    public XPermissionClient(Context context) {
        this.context = context;
    }

    public XPermissionClient(Activity activity) {
        this.activity = activity;
        this.context = activity;
    }

    public enum PermissionStatus {
        Error,//权限申请报错
        Granted,//授予
        Denied,//拒绝
        NeverGranted,//未授权这些权限
        PermanentlyDenied,//永久拒绝
    }

    public XPermissionClient setStrTopTipsTitle(String strTopTipsTitle) {
        this.strTopTipsTitle = strTopTipsTitle;
        return this;
    }

    public XPermissionClient setStrTopTipsContent(String strTopTipsContent) {
        this.strTopTipsContent = strTopTipsContent;
        return this;
    }

    public interface PermissionBack {
        void back(PermissionStatus permissionStatus, List<String>... permissions);

        void pre();
    }

    public XPermissionClient setShowPermissionDialogTopTips(boolean showPermissionDialogTopTips) {
        isShowPermissionDialogTopTips = showPermissionDialogTopTips;
        return this;
    }

    /**
     * 判断一个或多个权限是否全部授予了
     *
     * @param permissions
     * @return
     */
    public boolean isGranted(String... permissions) {
        return XXPermissions.isGranted(context, permissions);
    }


    /**
     * 判断某个权限是否为特殊权限
     * 获取没有授予的权限
     *
     * @param permissions
     * @return
     */
    public List<String> getDenied(String... permissions) {
        return XXPermissions.getDenied(context, permissions);
    }

    /**
     * 判断一个或多个权限是否被永久拒绝了
     *
     * @param permission
     * @return
     */
    public boolean isSpecial(String permission) {
        return XXPermissions.isSpecial(permission);
    }

    /**
     * @param activity
     * @param permissions
     * @return
     */
    public boolean isPermanentDenied(Activity activity, String... permissions) {
        return XXPermissions.isDoNotAskAgainPermissions(activity, permissions);
    }


    /**
     * 如果是被永久拒绝就跳转到应用权限系统设置页面
     *
     * @param activity
     * @param permissions
     */
    public void startPermissionActivity(Activity activity, List<String> permissions, PermissionBack... permissionBack) {
        if (permissionBack != null && permissionBack.length != 0) {
            XXPermissions.startPermissionActivity(activity, permissions, new OnPermissionPageCallback() {
                @Override
                public void onGranted() {
                    if (permissionBack != null) {
                        permissionBack[0].back(PermissionStatus.Granted);
                    }
                }

                @Override
                public void onDenied() {
                    if (permissionBack != null) {
                        permissionBack[0].back(PermissionStatus.Denied);
                    }
                }
            });
        } else {
            XXPermissions.startPermissionActivity(activity, permissions);
        }
    }

    /**
     * 返回权限名字用、分割
     *
     * @param permissionNames
     * @return
     */
    public String permissionListToString(List<String> permissionNames) {
        return PermissionNameConvert.listToString(PermissionNameConvert.permissionsToNames(activity, permissionNames));
    }


    /**
     * 申请获取XX权限
     *
     * @param permissions
     * @param permissionBack
     */
    public void getAppPermission(String[] permissions, PermissionBack permissionBack) {
        if (activity == null) {
            //权限申请失败
            if (permissionBack != null) {
                permissionBack.back(PermissionStatus.Error);
            }
            return;
        }
        mRequestFlag = true;
        XXPermissions.with(activity)
                .permission(permissions)
                .interceptor(new IPermissionInterceptor() {
                    @Override
                    public void launchPermissionRequest(@NonNull Activity activity, @NonNull List<String> allPermissions, @Nullable OnPermissionCallback callback) {
                        // 延迟 300 毫秒是为了避免出现 PopupWindow 显示然后立马消失的情况
                        // 因为框架没有办法在还没有申请权限的情况下，去判断权限是否永久拒绝了，必须要在发起权限申请之后
                        // 所以只能通过延迟显示 PopupWindow 来做这件事，如果 300 毫秒内权限申请没有结束，证明本次申请的权限没有永久拒绝
                        HANDLER.postDelayed(() -> {
                            if (!mRequestFlag) {
                                return;
                            }
                            showDialogTips();

                            if (permissionBack != null) {
                                permissionBack.pre();
                            }
                        }, 300);
                        IPermissionInterceptor.super.launchPermissionRequest(activity, allPermissions, callback);
                    }

                    @Override
                    public void grantedPermissionRequest(@NonNull Activity activity, @NonNull List<String> allPermissions, @NonNull List<String> grantedPermissions, boolean all, @Nullable OnPermissionCallback callback) {
                        //全部授予成功
                        if (all) {
                            if (permissionBack != null) {
                                permissionBack.back(PermissionStatus.Granted);
                            }
                        } else {
                            //部分授权成功，返回拒绝部分的权限
                            if (permissionBack != null) {
                                permissionBack.back(PermissionStatus.NeverGranted, getDeniedPermissions(allPermissions, grantedPermissions));
                            }
                        }
                        IPermissionInterceptor.super.grantedPermissionRequest(activity, allPermissions, grantedPermissions, all, callback);
                    }

                    @Override
                    public void deniedPermissionRequest(@NonNull Activity activity, @NonNull List<String> allPermissions, @NonNull List<String> deniedPermissions, boolean never, @Nullable OnPermissionCallback callback) {
                        IPermissionInterceptor.super.deniedPermissionRequest(activity, allPermissions, deniedPermissions, never, callback);
                    }

                    @Override
                    public void finishPermissionRequest(@NonNull Activity activity, @NonNull List<String> allPermissions, boolean skipRequest, @Nullable OnPermissionCallback callback) {
                        mRequestFlag = false;
                        dismissDialogTips();
                        IPermissionInterceptor.super.finishPermissionRequest(activity, allPermissions, skipRequest, callback);
                    }
                }).request(new OnPermissionCallback() {
                    //PS:如果在请求多个权限的情况下，这些权限不是被全部授予或者全部拒绝了，而是部分授权部分拒绝这种情况
                    //框架会先调用 **onDenied** 方法，再调用 **onGranted** 方法。其中我们可以通过 **onGranted** 方法中的 **all** 参数来判断权限是否全部授予了。

                    /**
                     * 如果用户全部授予只会调用 **onGranted** 方法
                     * @param permissions
                     * @param all
                     */
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {

                    }

                    /**
                     * 全部拒绝只会调用 **onDenied** 方法
                     * @param permissions
                     * @param never
                     */
                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        dismissDialogTips();
                        //是否被永久拒绝
                        if (never) {
                            //被永久拒绝，返回拒绝的权限
                            if (permissionBack != null) {
                                permissionBack.back(PermissionStatus.PermanentlyDenied, permissions);
                            }
                        } else {
                            //被拒绝，返回拒绝的权限
                            if (permissionBack != null) {
                                permissionBack.back(PermissionStatus.Denied, permissions);
                            }
                        }
                        OnPermissionCallback.super.onDenied(permissions, never);
                    }
                });

     /*  XXPermissions.with(activity)
               .permission(permissions)
               .interceptor(new IPermissionInterceptor() {
                   @Override
                   public void requestPermissions(Activity activity, List<String> allPermissions, OnPermissionCallback callback) {
                       showDialogTips();
                       if(permissionBack!=null){
                           permissionBack.pre();
                       }
                       IPermissionInterceptor.super.requestPermissions(activity, allPermissions, callback);
                   }

                   @Override
                   public void grantedPermissions(Activity activity, List<String> allPermissions, List<String> grantedPermissions, boolean all, OnPermissionCallback callback) {
                       dismissDialogTips();
                       //全部授予成功
                       if(all){
                           if(permissionBack!=null){
                               permissionBack.back(PermissionStatus.Granted);
                           }
                       }else{
                           //部分授权成功，返回拒绝部分的权限
                           if(permissionBack!=null){
                               permissionBack.back(PermissionStatus.NeverGranted,getDeniedPermissions(allPermissions,grantedPermissions));
                           }
                       }
                       IPermissionInterceptor.super.grantedPermissions(activity, allPermissions, grantedPermissions, all, callback);
                   }

                   @Override
                   public void deniedPermissions(Activity activity, List<String> allPermissions, List<String> deniedPermissions, boolean never, OnPermissionCallback callback) {
                       IPermissionInterceptor.super.deniedPermissions(activity, allPermissions, deniedPermissions, never, callback);
                   }
               }).request(new OnPermissionCallback() {
                   //PS:如果在请求多个权限的情况下，这些权限不是被全部授予或者全部拒绝了，而是部分授权部分拒绝这种情况
                   //框架会先调用 **onDenied** 方法，再调用 **onGranted** 方法。其中我们可以通过 **onGranted** 方法中的 **all** 参数来判断权限是否全部授予了。
                   *//**
         * 如果用户全部授予只会调用 **onGranted** 方法
         * @param permissions
         * @param all
         *//*
                   @Override
                   public void onGranted(List<String> permissions, boolean all) {

                   }

                   *//**
         * 全部拒绝只会调用 **onDenied** 方法
         * @param permissions
         * @param never
         *//*
                   @Override
                   public void onDenied(List<String> permissions, boolean never) {
                       dismissDialogTips();
                       //是否被永久拒绝
                       if(never){
                           //被永久拒绝，返回拒绝的权限
                           if(permissionBack!=null){
                               permissionBack.back(PermissionStatus.PermanentlyDenied,permissions);
                           }
                       }else{
                           //被拒绝，返回拒绝的权限
                           if(permissionBack!=null){
                               permissionBack.back(PermissionStatus.Denied,permissions);
                           }
                       }
                       OnPermissionCallback.super.onDenied(permissions, never);
                   }
               });*/
    }


    private List<String> getDeniedPermissions(List<String> allPermissions, List<String> grantedPermissions) {
        List<String> trans = allPermissions;
        trans.removeAll(grantedPermissions);
        return trans;
    }


    /**
     * 显示权限提示
     */
    private void showDialogTips() {
        if (!isShowPermissionDialogTopTips) {
            return;
        }

        if (permissionPopWindow != null && permissionPopWindow.isShow()) {
            return;
        }

        if (TextUtils.isEmpty(strTopTipsTitle) || TextUtils.isEmpty(strTopTipsContent)) {
            return;
        }

        getDialogPermissionTips()
                .setTitle(strTopTipsTitle)
                .setContent(strTopTipsContent)
                .show();

    }

    /**
     * 隐藏权限提示
     */
    private void dismissDialogTips() {
        if (!isShowPermissionDialogTopTips) {
            return;
        }

        if (permissionPopWindow == null) {
            return;
        }

        getDialogPermissionTips().dismiss();
    }


    private PermissionPopWindow getDialogPermissionTips() {
        if (permissionPopWindow == null) {
            permissionPopWindow = new PermissionPopWindow(context,(ViewGroup) activity.getWindow().getDecorView());
        }

        return permissionPopWindow;
    }

}
